package com.magic.controller.user;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.magic.auth.TokenFilter;
import com.magic.entity.user.Address;
import com.magic.entity.user.ExchangeHistory;
import com.magic.entity.user.Flower;
import com.magic.entity.user.User;
import com.magic.entity.user.UserGame;
import com.magic.result.Result;
import com.magic.service.user.UserService;
import com.magic.util.ValidUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

/**
 * ClassName: UserController <br/>
 * Function: user controller. <br/>
 * date: 2018年10月16日 上午9:09:53 <br/>
 * 
 * @author lishuai11
 * @version
 * @since JDK 1.8
 */
@Api(value = "用户管理")
@RestController
@RequestMapping("/user/manager/")
public class UserController {

	@Autowired
	UserService userService;

	/**
	 * 
	 * logout:(退出). <br/>
	 * 
	 * @author lishuai11
	 * @param request
	 * @return
	 * @since JDK 1.8
	 */
	@ApiOperation(value = "退出登陆", httpMethod = "DELETE", notes = "退出登陆")
	@ApiImplicitParam(name = "userId", value = "用户主键ID", required = true, dataType = "int", paramType = "path")
	@RequestMapping(value = "logout/{userId}", method = RequestMethod.DELETE)
	public Result logout(@PathVariable(name = "userId") int userId, HttpServletRequest request) {
		String token = request.getHeader(TokenFilter.AUTH_KEY).trim();
		return userService.logout(token, userId);
	}

	/**
	 * 
	 * addAddress:(添加地址). <br/>
	 * 
	 * @author lishuai11
	 * @param address
	 * @param result
	 * @return
	 * @since JDK 1.8
	 */
	@ApiOperation(value = "添加收货地址", httpMethod = "POST", notes = "添加收货地址")
	@ApiImplicitParam(name = "address", value = "收货地址请求体", required = true, dataType = "Address")
	@RequestMapping(value = "address", method = RequestMethod.POST)
	public Result addAddress(@RequestBody Address address, HttpServletRequest request) {
		String token = request.getHeader(TokenFilter.AUTH_KEY).trim();
		List<String> list = ValidUtil.validate(address);
		if (list != null && !list.isEmpty()) {
			StringBuilder errorString = new StringBuilder();
			list.forEach(row -> {
				errorString.append(row).append(";");
			});
			return Result.fail(Result.CLIENT_ERROR, errorString.toString());
		}
		return userService.addAddress(address, token);
	}

	/**
	 * 
	 * deleteAddress:(删除地址). <br/>
	 * 
	 * @author lishuai11
	 * @param addressId
	 * @return
	 * @since JDK 1.8
	 */
	@ApiOperation(value = "删除收货地址", httpMethod = "DELETE", notes = "删除收货地址")
	@ApiImplicitParam(name = "addressId", value = "收货地址id", required = true, dataType = "int", paramType = "path")
	@RequestMapping(value = "address/{addressId}", method = RequestMethod.DELETE)
	public Result deleteAddress(@PathVariable(name = "addressId") int addressId, HttpServletRequest request) {
		String token = request.getHeader(TokenFilter.AUTH_KEY).trim();
		return userService.deleteAddress(addressId, token);
	}

	/**
	 * 
	 * deleteAllAddress:(清空地址). <br/>
	 * 
	 * @author lishuai11
	 * @param userId
	 * @return
	 * @since JDK 1.8
	 */
	@ApiOperation(value = "清空收货地址", httpMethod = "DELETE", notes = "清空收货地址")
	@ApiImplicitParam(name = "userId", value = "用户id", required = true, dataType = "int", paramType = "path")
	@RequestMapping(value = "all/address/{userId}", method = RequestMethod.DELETE)
	public Result deleteAllAddress(@PathVariable(name = "userId") int userId, HttpServletRequest request) {
		String token = request.getHeader(TokenFilter.AUTH_KEY).trim();
		return userService.deleteAllAddress(userId, token);
	}

	/**
	 * 
	 * updateAddress:(更新地址). <br/>
	 * 
	 * @author lishuai11
	 * @param address
	 * @param result
	 * @return
	 * @since JDK 1.8
	 */
	@ApiOperation(value = "修改收货地址", httpMethod = "PUT", notes = "修改收货地址")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "addressId", value = "收货地址id", required = true, dataType = "int", paramType = "path"),
			@ApiImplicitParam(name = "address", value = "收货地址请求体", required = true, dataType = "Address") })
	@RequestMapping(value = "address/{addressId}", method = RequestMethod.PUT)
	public Result updateAddress(@PathVariable(name = "addressId") int addressId, @RequestBody Address address,
			HttpServletRequest request) {
		String token = request.getHeader(TokenFilter.AUTH_KEY).trim();
		List<String> list = ValidUtil.validate(address);
		if (list != null && !list.isEmpty()) {
			StringBuilder errorString = new StringBuilder();
			list.forEach(row -> {
				errorString.append(row).append(";");
			});
			return Result.fail(Result.CLIENT_ERROR, errorString.toString());
		}
		address.setAddressId(addressId);
		return userService.updateAddress(address, token);
	}

	/**
	 * 
	 * addressList:(地址列表). <br/>
	 * 
	 * @author lishuai11
	 * @return
	 * @since JDK 1.8
	 */
	@ApiOperation(value = "获取收货地址", httpMethod = "GET", notes = "获取收货地址")
	@ApiImplicitParam(name = "userId", value = "用户id", required = true, dataType = "int", paramType = "path")
	@RequestMapping(value = "address/{userId}", method = RequestMethod.GET)
	public Result address(@PathVariable(name = "userId") int userId, HttpServletRequest request) {
		String token = request.getHeader(TokenFilter.AUTH_KEY).trim();
		return userService.addressList(userId, token);
	}

	/**
	 * 
	 * getUser:(获取用户). <br/>
	 * 
	 * @author lishuai11
	 * @param userId
	 * @return
	 * @since JDK 1.8
	 */
	@ApiOperation(value = "查询用户", httpMethod = "GET", notes = "根据用户id查询用户")
	@ApiImplicitParam(name = "userId", value = "用户id", required = true, dataType = "int", paramType = "path")
	@RequestMapping(value = "{userId}", method = RequestMethod.GET)
	public Result getUser(@PathVariable(name = "userId") int userId, HttpServletRequest request) {
		String token = request.getHeader(TokenFilter.AUTH_KEY).trim();
		return userService.findByUserId(userId, token);
	}

	/**
	 * 
	 * updateUser:(更新用户). <br/>
	 * 
	 * @author lishuai11
	 * @param user
	 * @param result
	 * @return
	 * @since JDK 1.8
	 */
	@ApiOperation(value = "修改用户", httpMethod = "PUT", notes = "根据用户id修改用户信息（包括修改用户的昵称，头像，性别，手机号，市区）")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "userId", value = "用户id", required = true, dataType = "int", paramType = "path"),
			@ApiImplicitParam(name = "user", value = "用户信息请求体", required = true, dataType = "User") })
	@RequestMapping(value = "update/{userId}", method = RequestMethod.PUT)
	public Result updateUser(@PathVariable(name = "userId") int userId, @RequestBody User user,
			HttpServletRequest request) {
		String token = request.getHeader(TokenFilter.AUTH_KEY).trim();
		List<String> list = ValidUtil.validate(user);
		if (list != null && !list.isEmpty()) {
			StringBuilder errorString = new StringBuilder();
			list.forEach(row -> {
				errorString.append(row).append(";");
			});
			return Result.fail(Result.CLIENT_ERROR, errorString.toString());
		}
		user.setUserId(userId);
		return userService.updateUser(user, token);
	}

	@ApiOperation(value = "个人花种", httpMethod = "GET", notes = "根据用户id查询花种信息", response = Flower.class)
	@ApiImplicitParam(name = "userId", value = "用户id", required = true, dataType = "int", paramType = "path")
	@RequestMapping(value = "{userId}/flower", method = RequestMethod.GET)
	public Result seed(@PathVariable(name = "userId") int userId, HttpServletRequest request) {
		String token = request.getHeader(TokenFilter.AUTH_KEY).trim();
		return userService.flowerByUserId(userId, token);
	}

	@ApiOperation(value = "兑换记录", httpMethod = "GET", notes = "根据用户id查询兑换记录")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "userId", value = "用户id", required = true, dataType = "int", paramType = "path"),
			@ApiImplicitParam(name = "pageNum", value = "页码(默认0)", required = false, dataType = "int", defaultValue = "0", paramType = "query"),
			@ApiImplicitParam(name = "pageSize", value = "页大小(默认10)", required = false, dataType = "int", defaultValue = "10", paramType = "query") })
	@RequestMapping(value = "exchange/{userId}", method = RequestMethod.GET)
	public Result exchageHistory(@PathVariable(name = "userId") int userId,
			@RequestParam(defaultValue = "0", required = false) int pageNum,
			@RequestParam(defaultValue = "10", required = false) int pageSize, HttpServletRequest request) {
		String token = request.getHeader(TokenFilter.AUTH_KEY).trim();
		return userService.exchangeHistory(userId, pageNum, pageSize, token);
	}

	@ApiOperation(value = "点击兑换", httpMethod = "POST", notes = "点击兑换,生成兑换记录；兑换记录字段(status=①send:待发货②receive:待收货③end:已完成)")
	@ApiImplicitParam(name = "exchangeHistory", value = "兑换记录请求体", required = true, dataType = "ExchangeHistory")
	@RequestMapping(value = "exchange", method = RequestMethod.POST)
	public Result exchange(@RequestBody ExchangeHistory exchangeHistory, HttpServletRequest request) {
		String token = request.getHeader(TokenFilter.AUTH_KEY).trim();
		List<String> list = ValidUtil.validate(exchangeHistory);
		if (list != null && !list.isEmpty()) {
			StringBuilder errorString = new StringBuilder();
			list.forEach(row -> {
				errorString.append(row).append(";");
			});
			return Result.fail(Result.CLIENT_ERROR, errorString.toString());
		}
		return userService.exchange(exchangeHistory, token);
	}

	@ApiOperation(value = "用户游戏记录", httpMethod = "GET", notes = "游戏记录", response = UserGame.class, responseContainer = "list")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "userId", value = "用户id", required = true, dataType = "int", paramType = "path"),
			@ApiImplicitParam(name = "pageNum", value = "页码(默认0)", required = false, dataType = "int", defaultValue = "0", paramType = "query"),
			@ApiImplicitParam(name = "pageSize", value = "页大小(默认10)", required = false, dataType = "int", defaultValue = "10", paramType = "query") })
	@RequestMapping(value = "{userId}/game/history", method = RequestMethod.GET)
	public Result userGameHistory(@PathVariable(name = "userId") int userId,
			@RequestParam(defaultValue = "0", required = false) int pageNum,
			@RequestParam(defaultValue = "10", required = false) int pageSize, HttpServletRequest request) {
		String token = request.getHeader(TokenFilter.AUTH_KEY).trim();
		return userService.userGame(userId, pageNum, pageSize, token);
	}

	@ApiOperation(value = "当前用户参与游戏花种", httpMethod = "GET", notes = "当前用户参与游戏花种", response = UserGame.class)
	@ApiImplicitParams({
			@ApiImplicitParam(name = "userId", value = "用户id", required = true, dataType = "int", paramType = "path"),
			@ApiImplicitParam(name = "gameId", value = "游戏id", required = true, dataType = "int", paramType = "path") })
	@RequestMapping(value = "{userId}/game/{gameId}/seeds", method = RequestMethod.GET)
	public Result userGameSeeds(@PathVariable(name = "userId") int userId, @PathVariable(name = "gameId") int gameId,
			HttpServletRequest request) {
		String token = request.getHeader(TokenFilter.AUTH_KEY).trim();
		return userService.getUserGameSeeds(userId, gameId, token);
	}

}
